//
//  AppDelegate.m
//  HuaRun
//
//  Created by admin on 17/8/28.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarViewController.h"
#import "IQKeyboardManager.h"
#import "LoginViewController.h"
#import "Contact_DetailViewController.h"
#import "Company_DetailViewController2.h"
#import "Reachability+XHNNetState.h"
#import "XHNHudManager.h"
#import "UserModel.h"
#import <Bugtags/Bugtags.h>
#import "NSBundle+Language.h"
#import "EAIntroView.h"
#import "Add_Manual_ContactViewController.h"
#import "Add_Manual_CompanyViewController.h"
#import "TouchLockViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>


//测试
#import "EditPrivateInfoViewController.h"
#import "EditWorkInfoViewController.h"
#import "ChooseCountryViewController.h"
#import "ChooseAddressViewController.h"
#import "ChooseCompanyController1.h"
#import "ZLGestureLockViewController.h"


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
     [Bugtags startWithAppKey:@"ce343aeff60ce40ea0304c66066ef981"
              invocationEvent:BTGInvocationEventNone];
    NSLog(@"---%@ \n%@ %@", [NSString appCurVersion],
          [[NSUserDefaults standardUserDefaults] valueForKey:@"AppleLanguages"],
          NSStringFromCGRect( [UIScreen mainScreen].bounds));
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"]
        && ![[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] isEqualToString:@""]) {
        [NSBundle setLanguage:[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"]];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];

    // 设置相应的 ViewController
    BaseTabBarViewController *vc = [[BaseTabBarViewController alloc] init];

    NSString * appVerionLaunch = [NSString stringWithFormat:@"everLaunched%@",
                                  [NSString appCurVersion]];
    NSLog(@"%@", appVerionLaunch);

    LoginViewController *loginVC = [[LoginViewController alloc] init];
    UINavigationController * loginNav = [[UINavigationController alloc] initWithRootViewController:loginVC];
    
    weakself(ws);
    loginVC.clickBlock = ^(id result) {
        
        ws.window.rootViewController = vc;
    };

    if (![[NSUserDefaults standardUserDefaults] boolForKey:appVerionLaunch]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:appVerionLaunch];
        loginVC.isFirstLaunch = YES;
        
        self.window.rootViewController = loginNav;
    }else {
        //是否登录状态
        BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:isLoginState];
        if (isLogin) {
            
            self.window.rootViewController = vc;

        }else {
            self.window.rootViewController = loginNav;
        }
    }
    
    [self.window makeKeyAndVisible];
        
    [self configureKeyBoard];
//    [self checkIsServicesOnline];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:appVerionLaunch]) {

        //是否登录状态
        BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:isLoginState];
        if (isLogin) {
            [self isCanUseTouchIDWithVC:vc];
        }
    }

//    ZLGestureLockViewController *editInfovc = [[ZLGestureLockViewController alloc] initWithUnlockType:ZLUnlockTypeValidatePsw];
//    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:editInfovc];
//    self.window.rootViewController = nav;

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

    NSLog(@"hello");

}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"hello");

}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    NSLog(@"hello");

}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"hello");

}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSLog(@"hello");

}


/**
 //控制键盘
 // 详见http://www.jianshu.com/p/01c0682003a9
 */
- (void)configureKeyBoard {
    
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
//    [IQKeyboardManager sharedManager].shouldShowTextFieldPlaceholder = NO;
//    [IQKeyboardManager sharedManager].enableDebugging = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}


/** 检测网络状态是否可用*/
- (void)checkIsServicesOnline{

    Reachability* reach = [Reachability reachabilityWithHostname:kDomain];
    
    // Set the blocks
    reach.reachableBlock = ^(Reachability*reach)
    {
        // keep in mind this is called on a background thread
        // and if you are updating the UI it needs to happen
        // on the main thread, like this:
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"REACHABLE!");
        });
        [[NSNotificationCenter defaultCenter] postNotificationName:kReachAble object:nil];
    };
    
    reach.unreachableBlock = ^(Reachability*reach)
    {
        NSLog(@"UNREACHABLE!");
        [[NSNotificationCenter defaultCenter] postNotificationName:kReachUnAble object:nil];
    };
    
    // Start the notifier, which will cause the reachability object to retain itself!
    [reach startNotifier];
}

- (void)isCanUseTouchIDWithVC:(UIViewController *)vc {
    //创建LAContext
    LAContext *context = [[LAContext alloc] init];
    // 这个属性是设置指纹输入失败之后的弹出框的选项
//    context.localizedFallbackTitle = @"请输入密码";
    
    NSError *error = nil;
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        [self presentTouchIDPageWithVC:vc];
    }else {
        [self presentGestureLockPageWithVC:vc];
    }
    
}

- (void)presentTouchIDPageWithVC:(UIViewController *)vc{
    TouchLockViewController *editInfovc = [TouchLockViewController new];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:editInfovc];
    [vc presentViewController:nav animated:YES completion:^{
        NSLog(@"presentLoginMethod");
    }];
    
}

- (void)presentGestureLockPageWithVC:(UIViewController *)vc{
    ZLGestureLockViewController *editInfovc = [[ZLGestureLockViewController alloc] initWithUnlockType:ZLUnlockTypeValidatePsw];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:editInfovc];

    [vc presentViewController:nav animated:YES completion:^{
        NSLog(@"presentLoginMethod");
    }];
}


@end
